package com.peng.leetcode.search;

import java.util.Arrays;

/**
 * ThreeSumClosest
 * 16. 最接近的三数之和
 * https://leetcode.cn/problems/3sum-closest/
 *
 * @author: lupeng6
 * @create: 2023/3/13 13:50
 */
public class ThreeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        Integer ans = null;
        for (int i = 0; i < nums.length - 2; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == target) {
                    return sum;
                }
                if (ans == null || Math.abs(target - sum) < Math.abs(target - ans)) {
                    ans = sum;
                }
                if (sum > target) {
                    r--;
                } else {
                    l++;
                }
            }
        }
        return ans;
    }
}
